<?php

namespace App\Services\Chanjet;

use App\Models\Chanjet\TplusSaleGrossProfitAnalysisSummary;
use App\Models\Company;
use App\Models\Order\Salesorder;
use Illuminate\Support\Facades\Log;


/***
 *  远程拉取T+数据，方法入服务层改造。
 *  原有的TplusCommon 公共控制器方法保留，最新的拉取逻辑，以service getExternalData方法为准
 *  后续，通用方法使用service的 2025.06.27
 *
**/
class ChanjetExternalDataSync
{
    /***
     * @param $controllerName string 控制器
     * @param $org_id string T+账套id 获取的数据插入，需要cpid区分
     * @param $addRequestparam string 请求增加过滤参数 非必填
     * @param $token string 请求token  非必填
     * @param $return_array string 返回Response/array  非必填
     *
     *  请求t+报表 数据入库
     *  1. 获取控制器配置
     *  2. 拼接请求字段 请求条件
     *  3. 请求后,字段对应入库
     *
     *   定时任务/消息通知 携带token 请求数据. 返回 数组
     *
     *  单据类数据,取消定时任务拉取，改为消息回调入库，查询时 不需要单据日期条件，2025.06.03
     *
     * $controllerName  控制器（决定数据入哪个业务），必传
     * $org_id 畅捷通企业id(对应华坤cpid)
     * $addRequestparam (追加请求参数)
     * $token  （请求时，是否携带token）
     * $return_array (返回数据/消息)
     * $is_msg_notify (是否是消息通知数据入库)
     *
     */
    //public function getExternalData($controllerName= "",$org_id = "",$addRequestparam = [],$token="",$return_array=false,$is_msg_notify=false){
    public function getExternalData($data= []){
        $res = ['code' => '000','msg'=>''];
        //dump($addRequestparam);die;
        //$org_id = "",$addRequestparam = [],$token="",$return_array=false,$is_msg_notify=false
        if(!isset($data['controllerName'])){
            $res["code"] = "001";
            $res["msg"] = "业务控制器名不能为空";
            return $res;
        }
        if(!isset($data['org_id'])){
            $res["code"] = "001";
            $res["msg"] = "org_id不能为空";
            return $res;
        }
        if(!isset($data['addRequestparam'])){
            $data['addRequestparam'] = [];
        }
        if(!isset($data["return_array"])){
            $data["return_array"] = false;
        }
        if(!isset($data["token"])){
            $data["token"] = "";
        }
        if(!isset($data["is_msg_notify"])){
            $data["is_msg_notify"] = false;
        }
        //$is_msg_notify
        //请求参数
        $param = $this->getRequestParam($data["controllerName"],$data["addRequestparam"],$data["is_msg_notify"]);

        //请求
        $apiName = $this->getRequestApi($data["controllerName"]);//$config["config"]["queryApi"];

        //dump($param);
        //dump($org_id);die;
        $list = ChanjetRequest::getInstance()->$apiName($param,$data["org_id"],$data["token"]);
//        $list = '{"code":"0","message":"ok","data":{"TotalCount":6,"TotalPageNum":1,"Columns":["id","code","voucherdate","voucherdate1","busitype_name","partner_name","warehouse_name","pubuserdefnvc1","id1","rdrecorddetails_inventory_name","rdrecorddetails_inventory_specification","rdrecorddetails_sourcevouchercode","rdrecorddetails_sourcevouchertype_id","rdrecorddetails_sourcevouchertype_isautocreate","rdrecorddetails_sourcevouchertype_datatype","rdrecorddetails_sourcevouchertype_islowestpricecontrol"],"Rows":[["24","IC-2025-01-0001","2025\/01\/09","2025\/1\/9 0:00:00","\u5176\u4ed6",null,"\u534e\u4e3a\u5de5\u5382",null,"24","\u534e\u4e3amate70","5*5",null,null,null,null,null],["24","IC-2025-01-0001","2025\/01\/09","2025\/1\/9 0:00:00","\u5176\u4ed6",null,"\u534e\u4e3a\u5de5\u5382",null,"24","\u534e\u4e3amate70","5*5",null,null,null,null,null],["25","IC-2025-01-0002","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,null,null,"25","\u51e4\u68a8","80*90",null,null,null,null,null],["25","IC-2025-01-0002","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,null,null,"25","\u6a58\u5b50","","",null,null,null,null],["34","IC-2025-01-0003","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,"\u6c34\u679c\u4ed3",null,"34","\u83e0\u841d","","",null,null,null,null],["37","IC-2025-01-0004","2025\/01\/16","2025\/1\/16 0:00:00","\u5176\u4ed6",null,"\u897f\u5b89\u4ed3\u5e93",null,"37","iPhone16Pro",null,null,null,null,null,null],["38","IC-2025-01-0005","2025\/01\/17","2025\/1\/17 0:00:00","\u5176\u4ed6",null,"\u6c34\u679c\u4ed3",null,"38","\u6768\u6885","",null,null,null,null,null],["40","IC-2025-01-0006","2025\/01\/21","2025\/1\/21 0:00:00","\u53d7\u8d60",null,"\u51e4\u57ce\u7b2c\u4e00\u4ed3\u5e93",null,"40","\u7cbe\u81f4\u94a2123",null,null,null,null,null,null]]},"exception":null}';
//        $list = json_decode($list,true);
        //入库
        $res = $this->insertData($data["controllerName"],$list,$data["org_id"],$data["return_array"]);
        return $res;
    }
    /**
     *  请求条件
     *
     */
    public function getRequestParam($controllerName= "",$addRequestparam=[],$is_msg_notify=false){
        $config = ChanjetFinanceReportConfig::getConfig($controllerName);
        //dd($controllerName);
        $paramDic = $this->getTplusParamDic($config,$addRequestparam,$is_msg_notify);
        $paramField = $this->getTplusFields($config);
        //dump($paramField);die;
        if($config['config']["code"] != "report"){
            $param = [
                "pageSize"=>5000,
                "pageIndex"=>0,
                "selectFields"=>$paramField,
                "paramDic"=> $paramDic
            ];
        }else{
            //dd($config["config"]);
            $param = [
                "request" => [
                    "ReportName" => $config["config"]["ReportName"],
                    "PageIndex" => 1,
                    "PageSize" => 5000,
                    "SearchItems" => $paramDic,
                    "ReportTableColNames" => $paramField
                ]
            ];
        }
        //dd($param);
        return $param;
    }
    public function getRequestApi($controllerName =""){
        $config = ChanjetFinanceReportConfig::getConfig($controllerName);
        return $config["config"]["queryApi"];
    }

    public function getTplusFields($config = []){
        if($config["config"]["code"] != "report"){
            //dto 字段
            $field = $this->getTplusDtoSelectFields($config);

        }else{

            $field = $this->getTplusReportSelectFields($config);
        }

        return $field;
    }
    /***
     *   数据入库需要字段
     *
     */
    public function getTplusFieldsForInsert($config = []){
        if($config["config"]["code"] != "report"){
            //dto 字段
            $field = $this->getTplusDtoSelectFields($config,1);
        }else{
            //报表入库字段
            $field = $this->getTplusReportSelectFields($config,1);
        }

        return $field;
    }

    /**
     *  默认返回当前查询字段
     *  $is_all=0 返回 selectFields字段
     *  $is_all=1 返回 selectFields/ListFields/orgListFields/infoFields/orgInfoFields字段
     *
     */
    public function getTplusDtoSelectFields($config = [],$is_all = 0){
        $field_master = [];
        $field_slave = [];
        if($config["Field"]["listField"]){
            $field_master = $this->getStandardFieldsBySelectFields($config["Field"]["listField"]);

            $org_field_master = $config["Field"]["listField"];

            $selectFields = array_values($field_master);
        }
        //dump($org_field_master);die;
        if(isset($config["Field"]["infoField"])){
            $field_slave = $this->getStandardFieldsBySelectFields($config["Field"]["infoField"]);
            $org_field_slave = $config["Field"]["infoField"];

            $selectFields = array_merge($selectFields,array_values($field_slave));
        }
        if(isset($config["Field"]["info2Field"])){
            $field_slave_2 = $this->getStandardFieldsBySelectFields($config["Field"]["info2Field"]);
            $org_field_slave_2 = $config["Field"]["info2Field"];

            $selectFields = array_merge($selectFields,array_values($field_slave_2));
        }
        $res = [
            "selectFields" => $selectFields,
            "ListFields" => array_keys($field_master),
            "orgListFields" => array_keys($org_field_master),
            //"ListController" => $config["config"]["ListModel"],
        ];
        if(isset($config["Field"]["infoField"])){
            $res["infoFields"] = array_keys($field_slave);
            $res["orgInfoFields"] = array_keys($org_field_slave);
            //$res["InfoController"] = $config["config"]["InfoModel"];
        }
        if(isset($config["Field"]["info2Field"])){
            $res["info2Fields"] = array_keys($field_slave_2);
            $res["orgInfo2Fields"] = array_keys($org_field_slave_2);
            //$res["InfoController"] = $config["config"]["InfoModel"];
        }
        //dd($res);
        if(empty($is_all)){
            return $res["selectFields"];
        }else{
            return $res;
        }

    }
    /**
     *  返回查询字段/入库字段
     *
     */
    public function getTplusReportSelectFields($data = [],$is_all = 0){

        /***
         * 设置查询字段, 最多三张表
         *  "ReportTableColNames": "voucherDate,groupPartner"
         *
         */
        $selectFieldArr = [];
        $res = [];
        if(isset($data["config"]["ListModel"])){
            $field_master = $this->getStandardFieldsBySelectFields($data["Field"]["listField"]);

            $selectFieldArr = array_values($field_master);
            $res["ListFields"] = $data["Field"]["listField"];
        }

        if(isset($data["config"]["InfoModel"])){
            $field_slave = $this->getStandardFieldsBySelectFields($data["Field"]["infoField"]);
            $selectFieldArr = array_merge($selectFieldArr,array_values($field_slave));
            $res["InfoFields"] = $data["Field"]["infoField"];
        }
        $res["selectFields"] = implode(',',$selectFieldArr);
        //dd($res);
        if(empty($is_all)){
            return $res["selectFields"];
        }else{
            return $res;
        }

    }

    /**
     *  查询筛选条件
     *
     */
    public function getTplusParamDic($config = [],$filter = [],$is_msg_notify=false){
        $start_date= date("Y-m-d", strtotime("-60 day"));
        $end_date= date("Y-m-d");
        //if()
        if($config["config"]["code"] != "report"){
            //单据
            $res = [
                $config["config"]["code"].".VoucherDate" => [
                    [
                        "text"=>$start_date,
                        "value"=>$start_date,
                    ],
                    [
                        "text"=>$end_date,
                        "value"=>$end_date,
                    ],
                ]
            ];
            if($is_msg_notify){
                $res = [];
            }

            if(!empty($filter)){
                foreach($filter as $k=>$v){
                    $res[$config["config"]["code"].'.'.$k] = [
                        [
                            "text"=>$v,
                            "value"=>$v,
                        ],
                        [
                            "text"=>$v,
                            "value"=>$v,
                        ],
                    ];
                }
            }
            return $res;
        }else{
            //dump($filter);die;
            //报表
            $res = [];
            if(!empty($filter)){
                foreach ($filter as $k1=>$v1){
                    //dump($v1);die;
                    $countV1 = count($v1);
                    if($countV1 == 2){
                        $res[] = [
                            "ColumnName" => $v1[0],
                            "BeginDefault" => $v1[1],
                            "BeginDefaultText" => $v1[1],
                            "EndDefault" => $v1[1],
                            "EndDefaultText" => $v1[1],
                        ];
                    }else if($countV1 == 3){
                        $res[] = [
                            "ColumnName" => $v1[0],
                            "BeginDefault" => $v1[1],
                            "BeginDefaultText" => $v1[1],
                            "EndDefault" => $v1[2],
                            "EndDefaultText" => $v1[2],
                        ];
                    }else{
                        $res[] = [
                            "ColumnName" => $k1,
                            "BeginDefault" => $v1,
                            "BeginDefaultText" => $v1,
                            "EndDefault" => $v1,
                            "EndDefaultText" => $v1,
                        ];
                    }
                }
            }
            //dump($res);die;
            return $res;
        }
    }

    /***
     * 根据字符串获取 全路径
     * @param string
     * @return
     *
     */
    public static function getFullPath($name = "",$ident ='m'){
        if($ident == 'c'){
            return "\\App\\Http\\Controllers\\Chanjet\\" . $name;
        }
        if($ident == 'm'){
            return "\\App\\Models\\Chanjet\\" . $name;
        }
    }

    /**
     *   去除查档案查询字段的附加数据类型,只返回 两系统的字段对应关系
     *
     */
    public function getStandardFieldsBySelectFields($field = []){
        $resField = [];
        foreach($field as $keyItem => $item){
            $keyItemArr = explode("|",$keyItem);
            $itemArr = explode("|",$item);

            if(count($itemArr) > 1){
                $need_item = $itemArr[0];
            }else{
                $need_item = $item;
            }
            if(count($keyItemArr) > 1){
                $resField[$keyItemArr[0]] = $need_item;
            }else{
                $resField[$keyItem] = $need_item;
            }
        }
        return $resField;
    }

    public function insertData($controllerName="",$list=[],$org_id=0,$return_array=false){

        $config = ChanjetFinanceReportConfig::getConfig($controllerName);

        $Field = $this->getTplusFieldsForInsert($config);

        $cpid = Company::where('org_id',$org_id)->value('id');

        /***
         *  数据入库模式
         *  1.list 单表入库
         *  2.list-info 主从模式数据，使用当前方式数据入库
         *  3.list-info-info2 主-从-从2
         *
         */
        if($config['config']['code'] != 'report'){
            $data = []; //入库数据
            $data_info = []; //入库附表数据
            $data_info_2 = []; //入库第三张表
            //$paramField = $this->getTplusFields($config);
            //dump($paramField);die;

            //var_dump($list);die;
            if(isset($list["data"]["Rows"]) && !empty($list['data']["Rows"]))
            {
                $countListField = count($Field["ListFields"]);
                if(isset($Field["infoFields"])){
                    $countListFieldInfoField = count($Field["ListFields"]) + count($Field["infoFields"]);
                }
                foreach ($list["data"]["Rows"] as $key=>$item) {
                    //ListFields  $config["ListFields"]
                    $dataItem = [];
                    $data_info_item = [];
                    $data_info_item_2 = [];
                    foreach($Field["orgListFields"] as $fieldKey => $fieldVal){
                        if($item[$fieldKey]){
                            $fieldValArr = explode("|",$fieldVal);
                            if(count($fieldValArr) > 1){
                                $res = $this->formatDataForTplusVoucher($fieldValArr[1],$item[$fieldKey]);
                                $dataItem[$fieldValArr[0]] = $res;

//                                if($fieldValArr[1] == "datetime"){
//                                    $dataItem[$fieldValArr[0]] = strtotime($item[$fieldKey]);
//                                }
//                                if($fieldValArr[1] == "decimal"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.3f", ($item[$fieldKey] * 100));
//                                }
//                                if($fieldValArr[1] == "int"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.3f", $item[$fieldKey]);
//                                }
//                                if($fieldValArr[1] == "rate"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.2f", ($item[$fieldKey] * 100));
//                                }
                            }else{
                                $dataItem[$fieldValArr[0]] = $item[$fieldKey];
                            }
                            $dataItem['cpid'] = $cpid;
                        }
                    }
                    $data[] = $dataItem;
                    if(isset($Field["orgInfoFields"])){
                        foreach($Field["orgInfoFields"] as $fieldKey2 => $fieldVal2){
                            $newItemkey = $fieldKey2 + $countListField;
                            if($item[$newItemkey]){

                                $fieldVal2Arr = explode("|",$fieldVal2);

                                if(count($fieldVal2Arr) > 1){
                                    $res = $this->formatDataForTplusVoucher($fieldVal2Arr[1],$item[$newItemkey]);
                                    $data_info_item[$fieldVal2Arr[0]] = $res;
//                                    if($fieldVal2Arr[1] == "datetime"){
//                                        $data_info_item[$fieldVal2Arr[0]] = strtotime($item[$newItemkey]);
//                                    }
//                                    if($fieldVal2Arr[1] == "int"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.3f", $item[$newItemkey]);
//                                    }
//                                    if($fieldVal2Arr[1] == "decimal"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.3f", ($item[$newItemkey] * 100));
//                                    }
//                                    if($fieldVal2Arr[1] == "rate"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.2f", ($item[$newItemkey] * 100));
//                                    }
                                }else{
                                    $data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];
                                }
                                //$data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];
                            }
                            $data_info_item['cpid'] = $cpid;
                        }
                        $data_info[] = $data_info_item;
                    }else{
                        //保证主表 附表完全对应
                        $data_info[] = [];
                    }
                    //dd($Field);die;
                    if(isset($Field["orgInfo2Fields"])){
                        foreach($Field["orgInfo2Fields"] as $fieldKey3 => $fieldVal3){
                            $newItemkey = $fieldKey3 + $countListFieldInfoField;
                            if($item[$newItemkey]){

                                $fieldVal3Arr = explode("|",$fieldVal3);

                                if(count($fieldVal3Arr) > 1){
                                    $res = $this->formatDataForTplusVoucher($fieldVal3Arr[1],$item[$newItemkey]);
                                    $data_info_item_2[$fieldVal3Arr[0]] = $res;
//                                    if($fieldVal3Arr[1] == "datetime"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = strtotime($item[$newItemkey]);
//                                    }
//                                    if($fieldVal3Arr[1] == "int"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.3f", $item[$newItemkey]);
//                                    }
//                                    if($fieldVal3Arr[1] == "decimal"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.3f", ($item[$newItemkey] * 100));
//                                    }
//                                    if($fieldVal3Arr[1] == "rate"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.2f", ($item[$newItemkey] * 100));
//                                    }
                                }else{
                                    $data_info_item_2[$fieldVal3Arr[0]] = $item[$newItemkey];
                                }

                                //$data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];

                            }
                            $data_info_item_2['cpid'] = $cpid;
                        }
                        $data_info_2[] = $data_info_item_2;
                    }else{
                        //保证主表 附表完全对应
                        $data_info_2[] = [];
                    }

                }
//                dump($data);
//                dump($data_info);
//                dump($data_info_2);
//                die;
                //T+ 华坤数据对应处理完成,数据入库前
                $data = $this->insertDataBefore($data,$config['config']['code']);

                $List = self::getFullPath($config["config"]["ListModel"]);
                if(isset($config["config"]["InfoModel"])){
                    $Info = self::getFullPath($config["config"]["InfoModel"]);
                }
                if(isset($config["config"]["Info2Model"])){
                    $Info2 = $Info = self::getFullPath($config["config"]["Info2Model"]);
                }

                foreach ($data as $key=>$val){
                    //
                    $listExist = $List::where(["voucher_id"=>$val["voucher_id"],'cpid'=>$cpid])->first();
                    //主单据已经存在
                    if($listExist){
                        continue;
                    }else{
                        $main_id = $List::create($val)->id;
                        foreach ($data_info as $key2=>$val2){
                            if(isset($val2['voucher_id']) && ($val['voucher_id'] == $val2['voucher_id'])){
                                $insert_data_info = array_merge($val2,['main_id'=>$main_id]);
                                $Info::create($insert_data_info);
                            }
                        }
                        foreach ($data_info_2 as $key3=>$val3){
                            if(isset($val3['voucher_id']) && ($val['voucher_id'] == $val3['voucher_id'])){
                                $insert_data_info_2 = array_merge($val3,['main_id'=>$main_id]);
                                $Info2::create($insert_data_info_2);
                            }
                        }
                    }
                }
                if($return_array){
                    return ["code"=>"000","data"=>"入库成功"];
                }
                return response()->json(["code"=>"000","data"=>"入库成功"]);
            }else{
                if($return_array){
                    return ["code"=>"001","data"=>"获取数据失败,请检查"];
                }
                return response()->json(["code"=>"001","msg"=>"获取数据失败,请检查"]);
            }
        }else{
            /***
             *  报表入库
             *  1. list
             *  2. list-info
             */
            $List = self::getFullPath($config["config"]["ListModel"]);
            $listField = $config['Field']['listField'];
            if(isset($config['Field']['infoField'])){
                $infoField = $config['Field']['infoField'];
                $Info = self::getFullPath($config["config"]["InfoModel"]);
            }


            $data = []; //入库数据
            $data_info = []; //入库附表数据
            //判空 改为判定是否设置 2025.05.29
            if(isset($list["DataSource"]["Rows"]))
            {
                foreach ($list['DataSource']['Rows'] as $key=>$val){
                    $dataItem = [];
                    $dataInfoItem = [];
                    foreach ($listField as $key2=>$val2){

                        $countSeparaLeft = explode('|',$key2);
                        $countSepararight = explode('|',$val2);
                        //dd($countSepararight);
                        if(!isset($val[$countSepararight[0]])){
                            if(isset($countSepararight[1]) && !empty($val[$countSepararight[1]])){
                                $real_val = $val[$countSepararight[1]];
                            }else{
                                $real_val = '';
                            }
                        }else{
                            $real_val = $val[$countSepararight[0]];
                        }

                        if(count($countSeparaLeft) > 1){
                            $res = $this->formatDataForTplusVoucher($countSeparaLeft[1],$real_val);
                            $dataItem[$countSeparaLeft[0]] = $res;
//                            if($countSeparaLeft[1] == "decimal"){
//                                $dataItem[$countSeparaLeft[0]] = bcmul($real_val,100,3);
//                            }
//                            if($countSeparaLeft[1] == "datetime"){
//                                $dataItem[$countSeparaLeft[0]] = strtotime($real_val);
//                            }
//                            if($countSeparaLeft[1] == "int"){
//                                $dataItem[$countSeparaLeft[0]] = sprintf("%.3f", $real_val);
//                            }
//                            if($countSeparaLeft[1] == "rate"){
//                                $dataItem[$countSeparaLeft[0]] = bcmul($real_val,100,2);
//                            }
                        }else{
                            $dataItem[$countSeparaLeft[0]] = $real_val;
                        }
                        $dataItem['cpid'] = $cpid;
                    }
                    $data[] = $dataItem;
                    if(!empty($infoField)){
                        foreach ($infoField as $key3=>$val3){
                            $countSeparaLeft3 = explode('|',$key3);
                            $countSepararight3 = explode('|',$val3);
                            if(!isset($val[$countSepararight3[0]])){
                                $real_val2 = $val[$countSepararight3[1]];
                            }else{
                                $real_val2 = $val[$countSepararight3[0]];
                            }
                            if(count($countSeparaLeft) >1){
                                $res = $this->formatDataForTplusVoucher($countSeparaLeft[1],$real_val2);
                                $dataInfoItem[$countSeparaLeft[0]] = $res;
//                                if($countSeparaLeft[1] == "decimal"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = bcmul($real_val2,100,3);
//                                }
//                                if($countSeparaLeft[1] == "int"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = sprintf("%.3f", $real_val2);
//                                }
//                                if($countSeparaLeft[1] == "rate"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = bcmul($real_val2,100,2);
//                                }
                            }else{
                                $dataInfoItem[$countSeparaLeft3[0]] = $real_val2;
                            }
                            $dataInfoItem['cpid'] = $cpid;
                        }
                    }

                    $data_info[] = $dataInfoItem;

                }

                $data = $this->insertDataBeforeInReport($data,$config['config']['Model']);

                if($config["config"]["Model"] == 'TplusSaleGrossProfitAnalysisSummary'){
                    $data = $this->grossProfitCumul($data);
                    //上月15号，之前的毛利，认为就不再变化了
                    $last_month_middle = date('Y-m-d', strtotime(date('Y-m-15') . ' -1 month'));
                    //先查 在写
                    foreach ($data as $key=>$val){
                        $TplusSaleGrossProfitAnalysisSummary = TplusSaleGrossProfitAnalysisSummary::where(['cpid'=>$val['cpid'],'voucher_code'=>$val['voucher_code']])->first();
                        if($TplusSaleGrossProfitAnalysisSummary){
                            $TplusSaleGrossProfitAnalysisSummary->gross_profit = $val["gross_profit"];
                            $TplusSaleGrossProfitAnalysisSummary->gross_profit_rate = $val["gross_profit_rate"];
                            $TplusSaleGrossProfitAnalysisSummary->update_at = time();
                            //$TplusSaleGrossProfitAnalysisSummary->create_at = time();
                            //比对Tplus 如果是上个月的数据，毛利就确定了,不再更新
                            if($last_month_middle > $val["voucher_date"]){
                                $TplusSaleGrossProfitAnalysisSummary->is_final_profit = '1';
                            }
                            $TplusSaleGrossProfitAnalysisSummary->save();
                            $insertIds[] = $TplusSaleGrossProfitAnalysisSummary['id'];
                        }else{
                            $val['create_at'] = time();
                            if($last_month_middle > $val["voucher_date"]){
                                $val['update_at'] = time();
                                $val['is_final_profit'] = '1';
                            }
                            $main_id = $List::create($val)->id;
                            $insertIds[] = $main_id;
                        }
                    }
                }else{
                    //写库
                    foreach ($data as $key=>$val){
                        $main_id = $List::create($val)->id;
                        $insertIds[] = $main_id;
                        //dump($main_id);die;
                        if(!empty($data_info[$key])){
                            foreach ($data_info as $key2=>$val2){
                                //var_dump($val2);die;
                                $val2['main_id'] = $main_id;
                                $Info::create($val2);
                            }
                        }
                    }
                }
                if($return_array){
                    return ["code"=>"000","data"=>$insertIds,"msg"=>"入库成功"];
                }else{
                    return response()->json(["code"=>"000","msg"=>"入库成功"]);
                }
            }else{
                //数据返回空,不判定失败
                if($return_array){
                    return ["code"=>"001","msg"=>"获取数据失败,请检查"];
                }
                return response()->json(["code"=>"001","msg"=>"获取数据失败,请检查"]);
            }
        }

    }
    /***
     *   T+单据同步华坤，数据格式化落库
     *
     **/
    public function formatDataForTplusVoucher($format_symbol='int',$format_number = ''){
        //datetime decimal int rate
        $res = '';
        if($format_symbol == "datetime") $res = strtotime($format_number);
        if($format_symbol == "decimal") $res = mathfuncmoney('mul',$format_number,100,2);
        if($format_symbol == "int") $res = sprintf("%.3f", $format_number);
        if($format_symbol == "rate") $res = round(bcmul($format_number,100,6),2);
        if(strpos($format_symbol,'float') !== false){
            $format_symbol_arr = explode(':',$format_symbol);
            $scale = $format_symbol_arr[1]??'3';
            $format_number = bcmul($format_number,1,$scale);
            $res = number_format($format_number,$scale,'.','');
        }
        return $res;
    }
    /**
     *   单据类数据,入库前 数据处理
     *
     *
     */
    protected function insertDataBefore($data = [] ,$code = ''){
        if(empty($data) || empty($code)){
            return $data;
        }
        if($code == "SaleInvoice"){
            foreach ($data as &$item){
                if(isset($item["source_voucher_code"])){
                    $source_voucher_code_arr = explode("|",$item["source_voucher_code"]);
                    //查询销售发票业务, sales_order
                    if(isset($source_voucher_code_arr[1])){
                        $Salesorder = Salesorder::where('id',$source_voucher_code_arr[1])->first();
                        $item["order_number"] = isset($Salesorder["order_number"])?$Salesorder["order_number"]:'';//销售订单号
                        $item["document_number"] = isset($source_voucher_code_arr[0])?$source_voucher_code_arr[0]:'';//出库单单号
                        $item["settlement_company"] = isset($Salesorder["settlement_company"])?$Salesorder["settlement_company"]:'';//结算公司
                    }
                }
            }
        }
        return $data;
    }
    /**
     *   报表类数据,入库前 数据处理
     *
     *
     */
    protected function insertDataBeforeInReport($data = [] ,$model = ''){
        if(empty($data) || empty($model)){
            return $data;
        }
        if(in_array($model,["TplusSaleGrossProfitAnalysisSummary","TplusSaleGrossProfitAnalysis"])){
            foreach ($data as &$item){
                if(isset($item["voucher_code"])){
                    $source_voucher_code_arr = explode("|",$item["voucher_code"]);
                    if(isset($source_voucher_code_arr[0])){
                        $item["outbound_voucher_code"] = $source_voucher_code_arr[0];
                    }
                }
//                if($model == "TplusSaleGrossProfitAnalysisSummary"){
//                    $item['create_at'] = time();
//                }
            }
        }
        return $data;
    }
    /***
     *  销售毛利存在相同单据编号，多条数据情况；先列表去重累计。在入库
     *
    */
    /***
     * 销售毛利分析表 返回数据，重复的进行累加处理
     *
     *
     */
    public function grossProfitCumul($data =[]){
        $unique_voucher_code = [];
        foreach ($data as $key=>$val){
            if(!in_array($val['voucher_code'],array_values($unique_voucher_code))){
                $unique_voucher_code[$key] = $val['voucher_code'];
            }else{
                //存在重复 毛利累加
                $voucher_key = array_search($val['voucher_code'],$unique_voucher_code);
                $data[$voucher_key]['amount'] += $val['amount'];

                $data[$voucher_key]['tax'] += $val['tax'];
                $data[$voucher_key]['taxAmount'] += $val['taxAmount'];
                $data[$voucher_key]['accrued_rece_writeoff_amount'] += $val['accrued_rece_writeoff_amount'];
                $data[$voucher_key]['discount'] += $val['discount'];
                $data[$voucher_key]['have_outbound_cost'] += $val['have_outbound_cost'];
                $data[$voucher_key]['no_outbound_cost'] += $val['no_outbound_cost'];
                $data[$voucher_key]['total_cost'] += $val['total_cost'];
                $data[$voucher_key]['fee_cost_share'] += $val['fee_cost_share'];
                $data[$voucher_key]['no_fee_cost_share'] += $val['no_fee_cost_share'];
                $data[$voucher_key]['total_fee'] += $val['total_fee'];
                $data[$voucher_key]['gross_profit'] += $val['gross_profit'];
                $mult_gross_profit_rate = mathfunc('add',$data[$voucher_key]['gross_profit_rate'],$val['gross_profit_rate']);
                $data[$voucher_key]['gross_profit_rate'] = mathfunc('div',$mult_gross_profit_rate,2,2);
                unset($data[$key]);
            }
        }
        return array_values($data);
    }
}
